package cn.fetosoft.woodpecker.controller;

import cn.fetosoft.woodpecker.core.data.entity.BaseElement;
import cn.fetosoft.woodpecker.core.data.entity.Report;
import cn.fetosoft.woodpecker.core.data.entity.TestResult;
import cn.fetosoft.woodpecker.core.data.form.ReportForm;
import cn.fetosoft.woodpecker.core.data.form.TestResultForm;
import cn.fetosoft.woodpecker.core.data.service.ReportService;
import cn.fetosoft.woodpecker.core.data.service.TestResultService;
import cn.fetosoft.woodpecker.core.enums.DateFormatEnum;
import cn.fetosoft.woodpecker.core.util.Constant;
import cn.fetosoft.woodpecker.core.util.MenuTree;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author guobingbing
 * @version 1.0
 * @wechat t_gbinb
 * @create 2021/6/24 17:00
 */
@Slf4j
@Controller
@RequestMapping("/auth/test/result")
public class TestResultController {

	@Autowired
	private TestResultService testResultService;
	@Autowired
	private ReportService reportService;

	/**
	 * 测试结果树
	 * @param body
	 * @return
	 */
	@RequestMapping("/getSampleTree")
	@ResponseBody
	public String getSampleTree(@RequestBody String body){
		MenuTree root = new MenuTree(Constant.ROOT_PARENT_ID, "执行结果树", "");
		JSONObject json = JSON.parseObject(body);
		String planId = json.getString("planId");
		String testId = json.getString("testId");
		String threadId = json.getString("threadId");

		TestResultForm form = new TestResultForm();
		form.setPlanId(planId);
		form.setTestId(testId);
		form.setThreadId(threadId);
		form.setRows(5000);
		form.setAscField("id");
		try {
			List<TestResult> list = testResultService.selectListByForm(form, TestResult.class);
			this.recursionTree(root, list);
		} catch (Exception e) {
			log.error("getSampleTree", e);
		}
		return "[" + JSON.toJSONString(root) + "]";
	}

	private void recursionTree(MenuTree parent, List<TestResult> list){
		List<TestResult> children = list.stream().filter(e-> e.getParentId().equals(parent.getId()))
				.sorted(Comparator.comparingLong(BaseElement::getCreateTime))
				.collect(Collectors.toList());
		if(!CollectionUtils.isEmpty(children)){
			for(TestResult r : children){
				MenuTree child = new MenuTree(r.getId(), r.getName(), r.getCategory());
				if(r.getErrorCount()>0){
					child.setIconCls("icon-error");
				}else{
					child.setIconCls("icon-success");
				}
				this.recursionTree(child, list);
				parent.addChild(child);
			}
		}
	}

	/**
	 * 查询结果详情
	 * @param id
	 * @return
	 */
	@GetMapping("/detail")
	@ResponseBody
	public String getSampleResult(@RequestParam String id){
		Result<TestResult> result = Result.successResult();
		if(StringUtils.isNotBlank(id) && id.length()>8) {
			TestResult r = testResultService.findById(id, TestResult.class);
			if(r.getStartTime()>0){
				r.setStartTimeFmt(DateFormatEnum.YMD_HMS_SSS.timestampToString(r.getStartTime()));
			}
			if(r.getEndTime()>0){
				r.setEndTimeFmt(DateFormatEnum.YMD_HMS_SSS.timestampToString(r.getEndTime()));
			}
			result.setObj(r);
		}
		return result.toString();
	}

	/**
	 * 查询聚合报表
	 * @param form
	 * @return
	 */
	@RequestMapping("/getAggReportList")
	@ResponseBody
	public String getAggReportList(@ModelAttribute ReportForm form){
		Result<JSONObject> result = Result.errorResult();
		form.setAscField("createTime");
		try {
			JSONObject json = new JSONObject();
			List<Report> list = reportService.selectListByForm(form, Report.class);
			json.put("total", list.size());
			json.put("rows", list);
			result.setObj(json);
			result.setStatus(Result.SUCCESS);
		} catch (Exception e) {
			result.setErrorMsg(e.getMessage());
			log.error("getAggReportList", e);
		}
		return result.toString();
	}
}
